<?php

namespace App\Jobs;

use App\Modules\Jobs\Services\UpdateSelfRecoAverageService;
use App\Modules\Jobs\Services\UpdateSelfRecoService;
use App\Modules\Jobs\Services\UpdateUserAverageService;
use App\Modules\Jobs\Services\UpdateUserDetailService;
use App\Modules\User\Services\UserTaskDetailService;
use Illuminate\Bus\Queueable;
use Illuminate\Queue\SerializesModels;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Support\Facades\Log;

class SelfRecomend implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    protected $data;
    protected $action;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($action,$param)
    {
        //
        $this->data = $param;
        $this->action = $action;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {
        //
        try{
            $data = $this->data;
            $action = $this->action;
            if($action == 'selfRecomend') {
                UpdateSelfRecoService::RecommendTimes($data->uid);
                UpdateSelfRecoAverageService::RecommendAllTimes();
                UpdateSelfRecoAverageService::RecommendAllUserNum();
            }elseif($action == 'viewRec') {
                UpdateSelfRecoService::RecommendReadTimes($data->uid);
                UpdateSelfRecoAverageService::updateRecommendAllReadTimes();
                $time_diff = (strtotime($data->view_time) - strtotime($data->created_at))/3600;
                UpdateUserDetailService::updateDuration($data->uid,$time_diff);
                UpdateUserAverageService::UpdateAllHandleDuration($time_diff);
            }elseif ($action == 'adopt') {
                UpdateUserDetailService::UpdateUserAdoptTotal($data->uid);
                UpdateUserAverageService::getUserPickTotal();
            }else{
                Log::error('SelfRecommend queue error: No that action');
            }
        }catch (\Exception $e){
            Log::error('selfReco Queue error'.($e->getCode()).($e->getMessage()));
        }
        Log::info("SelfReco:executed!".json_encode($data,JSON_UNESCAPED_UNICODE));
    }
}
